/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cjt2325.cameraview.slice;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

import com.cjt2325.cameralibrary.JCameraView;
import com.cjt2325.cameralibrary.listener.JCameraListener;
import com.cjt2325.cameralibrary.util.FileUtil;
import com.cjt2325.cameralibrary.util.LogUtil;
import com.cjt2325.cameralibrary.util.ResUtils;
import com.cjt2325.cameraview.MainAbility;
import com.cjt2325.cameraview.ResourceTable;
import com.cjt2325.cameraview.listener.PermissionInterface;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.media.image.PixelMap;
import ohos.security.SystemPermission;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Main AbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice implements PermissionInterface {
    private JCameraView mJCameraView;
    private boolean isHavePermission;
    private List<String> mPermissions =
            new LinkedList<>(
                    Arrays.asList(
                            SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE));

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Ability ability = getAbility();
        if (ability instanceof MainAbility) {
            ((MainAbility) ability).setPermissionListener(this);
        }
        getWindow().setTransparent(true);
        Component component = findComponentById(ResourceTable.Id_jcameraview);
        if (component instanceof JCameraView) {
            mJCameraView = (JCameraView) component;
            mJCameraView.setSaveVideoPath(getFilesDir() + File.separator + "JCamera");
            mJCameraView.setIconLeftAndRight(
                    ResUtils.getVectorDrawable(getAbility(), ResourceTable.Graphic_ic_back),
                    ResUtils.getVectorDrawable(getAbility(), ResourceTable.Graphic_ic_photo));
            mJCameraView.setTip("自定义中间提醒标题");
            mJCameraView.setErrorListener(
                    (errorString, type) -> LogUtil.error(LogUtil.DEFAULT_TAG, "errorString:" + errorString));
            mJCameraView.setJCameraListener(
                    new JCameraListener() {
                        @Override
                        public void captureSuccess(PixelMap bitmap) {
                            String filUrl = FileUtil.saveBitmap("JCamera", bitmap, getContext());
                            Intent fileIntent = new Intent();
                            fileIntent.setParam("PHOTO_URL", filUrl);
                            setResult(fileIntent);
                            terminate();
                        }

                        @Override
                        public void recordSuccess(String url) {
                            LogUtil.error(LogUtil.DEFAULT_TAG, "recordSuccess");
                        }
                    });
            mJCameraView.setLeftClickListener(
                    () -> {
                        setResult(new Intent());
                        terminate();
                    });
            mJCameraView.setRightClickListener(() -> LogUtil.info(LogUtil.DEFAULT_TAG, "Click Right"));
            reqPermissions();
        }
    }

    private void reqPermissions() {
        mPermissions.removeIf(perS -> verifySelfPermission(perS) == PERMISSION_GRANTED || !canRequestPermission(perS));
        if (mPermissions.isEmpty()) {
            isHavePermission = true;
        }
    }

    private void handCamera() {
        isHavePermission = false;
        LogUtil.error(LogUtil.DEFAULT_TAG, "handCamera");
        if (mJCameraView != null) {
            mJCameraView.onResume();
        }
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        LogUtil.error(LogUtil.DEFAULT_TAG, "onBackPressed");
        setResult(new Intent());
    }

    @Override
    public void onReqFinish() {
        isHavePermission = true;
        handCamera();
    }

    @Override
    public void onActive() {
        super.onActive();
        getWindow().setStatusBarVisibility(Component.INVISIBLE);
        handCamera();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        if (mJCameraView != null) {
            mJCameraView.onPause();
        }
    }
}
